package com.example.demo.project.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.project.entity.Files;
import com.example.demo.project.mapper.FileMapper;
import com.example.demo.project.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;
    @Value("${files.upload.path}")
    private String fileUploadPath;
    @Value("${files.down.path}")
    private String fileDownPath;
    @Resource
    private FileMapper fileMapper;
    //新增和修改
    @PostMapping("/save")
    public Result save(@RequestBody Files files){
        return Result.success(fileService.saveOrUpdate(files));
    }
    @GetMapping("/list")
    public Result findAll(){
        return Result.success(fileService.list());
    }
    @GetMapping("/delete")
    public Result delete(@RequestParam String[] id){
        Collection ids = Arrays.asList(id);
        return Result.success(fileService.removeByIds(ids));
    }
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "1") Long pageNum,
                           @RequestParam(defaultValue = "4") Long pageSize,
                           @RequestParam(defaultValue = "") String name
//                                   @RequestParam(defaultValue = "") String age
    ){
        IPage<Files> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
//        if(!"".equals(age)){
//            queryWrapper.like("age",age);
//        }
//        queryWrapper.or().like("age",age);
        return Result.success(fileService.page(page,queryWrapper));
    }
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        // 定义文件的唯一标识（前缀）
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid = uuid+ StrUtil.DOT+type;
        File uploadFile = new File(fileUploadPath+fileUuid);
        File parentFile = uploadFile.getParentFile();
        System.out.println(parentFile.toString()+"+++++++++++++++++++++++++");
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        file.transferTo(uploadFile);
        String url;
        String md5 = SecureUtil.md5(uploadFile);
        Files dbFiles = getFileByMd5(md5);
        if(dbFiles !=null){
            url = dbFiles.getUrl();
            uploadFile.delete();
        }else{
            url=fileDownPath+fileUuid;
//            url = "http://193.112.118.108:8082/file/"+fileUuid;
//              url = "http://localhost:8080/file/"+fileUuid;
        }
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);
        return Result.success(url);
    }
    @GetMapping("/{fileUUID}")
    public Result download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException{
        File uploadFile = new File(fileUploadPath+fileUUID);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
        return Result.success();
    }
    private Files getFileByMd5(String md5){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5",md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size()==0?null:filesList.get(0);
    }
}
